package com.alpha.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alpha.bom.Professor;
import com.alpha.dao.StudentDao;

/**
 * Servlet implementation class ClassListServlet
 */
@WebServlet("/StudentsAdminServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class StudentsAdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(StudentsAdminServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StudentsAdminServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" get method started.");
		
		Professor professor = null;
		String message=null;
		String success = null;
		String error = null;
		
		if(request.getParameter("success")!=null){
			success = request.getParameter("success");
		} else if(request.getParameter("error")!=null){
			error = request.getParameter("error");
		} else if(request.getParameter("message")!=null){
			message = request.getParameter("message");
		}
		
		//should set the professor's students from the database
		HttpSession session = request.getSession();
		if(session.getAttribute("user")!=null){
			professor = (Professor)session.getAttribute("user");
		}
		
		StudentDao sDao = new StudentDao();
				
		try {
			professor.setStudents(sDao.retrieveStudentsByProfessorId(professor.getUserId()));
		} catch (NamingException e) {
			logger.error(e.getMessage());
			return;
		} catch (SQLException e) {
			logger.error(e.getMessage());
			return;
		}
		if(error!=null){
			response.sendRedirect("StudentsAdmin.jsp?error="+error);
		} else if(success!=null){
			response.sendRedirect("StudentsAdmin.jsp?success="+success);
		} else if(message!=null){
			response.sendRedirect("StudentsAdmin.jsp?message="+message);
		} else {
			response.sendRedirect("StudentsAdmin.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
